package com.qiao.dfw.loggic.login;

import com.qiao.dfw.config.SpringBeanUtil;
import com.qiao.dfw.dao.PlayerMapper;
import com.qiao.dfw.entity.Player;
import com.qiao.dfw.entity.PlayerLocal;
import com.qiao.dfw.loggic.ATask;
import com.qiao.dfw.loggic.ECode;
import com.qiao.dfw.manager.LoggerManager;
import com.qiao.dfw.manager.PlayerManager;
import com.qiao.dfw.network.ConnectionManager;
import com.qiao.dfw.proto.Login;
import com.qiao.dfw.thread.EThreadType;
import com.qiao.dfw.thread.ThreadManager;

import java.util.Objects;

public class RegisterTask extends ATask<Login.UserRegisterRequest> {
    @Override
    public void execute0() {
        LoggerManager.info("收到 Register %s,线程id: %s 对象 %s ", request.toString(), Thread.currentThread().getName(), this);
/*        PlayerMapper mapper = SpringBeanUtil.getBean(PlayerMapper.class);
        Player user = mapper.getPlayerByName(request.getUsername());*/

        Player user = PlayerManager.get(request.getUsername());

        if (user != null) {
            // 通知客户端,账号已存在
            Login.UserRegisterResponse.Builder builder = Login.UserRegisterResponse.newBuilder();
            builder.setSuccess(false);
            builder.setMsg("账号已存在");
            sendMsg(builder.build().toByteArray());
            return;
        }
        user = new Player();
        user.username = request.getUsername();
        user.password = request.getPassword();
        user.nickname = "用户" + request.getUsername();

        // Date date = new Date();
        // SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // user.createTime = dateFormat.format(date);
        // 存数据库
        PlayerManager.add(user);
        // 缓存
        conn.player = user;
        conn.player.local = PlayerLocal.Register;
        ConnectionManager.addNetConn(conn);

        Login.UserRegisterResponse.Builder build = Login.UserRegisterResponse.newBuilder();
        build.setSuccess(true);
        build.setMsg("注册成功");
        sendMsg(build.build().toByteArray());
    }

    @Override
    public ECode getCode() {
        return ECode.Register;
    }


    public int getThreadIndex() {
        String username = request.getUsername();
        int hash = Objects.hash(username);
        return ThreadManager.getThreadIndex(EThreadType.Login, hash);
    }
}
